package cn.itcast.bos.web.base.action;

import domain.base.Courier;
import domain.base.FixedArea;
import cn.itcast.bos.service.base.CourierService;
import cn.itcast.bos.service.base.FixedAreaService;
import cn.itcast.crm.domain.Customer;
import com.opensymphony.xwork2.ActionContext;
import org.apache.commons.lang3.StringUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.struts2.convention.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.ws.rs.core.MediaType;
import java.util.*;

/**
 * Created by Administrator on 2017/7/14/014.
 */
@ParentPackage("json-default")
@Namespace("/")
@Controller
@Actions
@Scope("prototype")
public class FixedAreaAction extends BaseAction<FixedArea,FixedAreaService> {

    @Autowired
    CourierService courierService;

    FixedArea fixedArea = new FixedArea();
    //模型驱动接受关联和未关联客户
    private Integer[] orphanIds;

    private Integer[] customerIds;

    //接受关联的快递员和收派时间信息
    private Integer courierId;

    private Integer takeTimeId;

    public void setCourierId(Integer courierId) {
        this.courierId = courierId;
    }

    public void setTakeTimeId(Integer takeTimeId) {
        this.takeTimeId = takeTimeId;
    }

    public void setOrphanIds(Integer[] orphanIds) {
        this.orphanIds = orphanIds;
    }

    public void setCustomerIds(Integer[] customerIds) {
        this.customerIds = customerIds;
    }

    @Action(value = "fixedArea_save",results = {
            @Result(name = "success",type = "redirect",location = "/pages/base/fixed_area.html")
    })
    public String save() {
        service.save(model);
        return SUCCESS;
    }

    @Action(value = "fixedArea_pageQuery",results = {
            @Result(name = "success",type = "json")
    })
    public String pageQuery() {
        Specification<FixedArea> specification = new Specification<FixedArea>() {
            @Override
            public Predicate toPredicate(Root<FixedArea> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> list = new ArrayList<>();
                if (StringUtils.isNotBlank(fixedArea.getId())){
                    //断言 表达的是Where 之后的语句,这里相当于是动态拼接SQL语句
                    //等于name = %?%,xxx
                    Predicate p1 = cb.equal(root.get("id").as(String.class),fixedArea.getId());
                    list.add(p1);
                }
                if(StringUtils.isNotBlank(fixedArea.getCompany())){
                    //这里可以用like进行模糊查询
                    Predicate p2 = cb.like(root.get("company").as(String.class),'%'+fixedArea.getCompany()+'%');
                    list.add(p2);
                }

                return cb.and(list.toArray(new Predicate[0]));
            }

        };
        //封装page和row信息
        Pageable pageable = new PageRequest(page-1,rows);
        //通过继承JpaSpecification接口使其findAll方法获得带条件检索功能
        Page<FixedArea> pageData = service.findAll(specification,pageable);
        Map<String,Object> result = new HashMap<>();
        result.put("total",pageData.getNumberOfElements());
        result.put("rows",pageData.getContent());
        ActionContext.getContext().getValueStack().push(result);
        return SUCCESS;
    }

    @Action(value = "customer_find_associated",results = {
            @Result(name = "success",type = "json")
    })
    public String findAssociated(){
        String address = "http://localhost:8080/crm/service/customerService/associated_customers"+ "/" + model.getId();
        Collection<? extends Customer> collection = WebClient.create(address).accept(MediaType.APPLICATION_JSON).getCollection(Customer.class);
        System.out.println(collection.toString());
        ActionContext.getContext().getValueStack().push(collection);
        return SUCCESS;
    }

    @Action(value = "customer_find_orphan",results = {
            @Result(name="success",type = "json")
    })
    public String findOrphan(){
        String address = "http://localhost:8080/crm/service/customerService/orphan_customers";
        Collection<? extends Customer> collection = WebClient.create(address).accept(MediaType.APPLICATION_JSON).getCollection(Customer.class);
        ActionContext.getContext().getValueStack().push(collection);
        return SUCCESS;
    }

    @Action(value = "customer_readyToAssociation",results = {
            @Result(name = "success",type = "redirect",location = "./pages/base/fixed_area.html")
    })
    public String associationCustomers(){
        String address = "http://localhost:8080/crm/service/customerService/associationCustomers";
        List<Integer> orphan = Arrays.asList(orphanIds);
        List<Integer> customer = Arrays.asList(customerIds);
        WebClient.create(address).accept(MediaType.APPLICATION_JSON).query("orphanIds",orphan)
                .query("customerIds",customer).query("ids",model.getId()).put(null);
        return SUCCESS;
    }

    @Action(value = "courier_findUnassociated",results = {
            @Result(name = "success",type = "json")
    })
    public String findUnassociated(){
        List<Courier> couriers = courierService.findUnassociated();
        ActionContext.getContext().getValueStack().push(couriers);
        return SUCCESS;
    }


    @Action(value = "fixedArea_readyToAssociationCourier",results = {
            @Result(name = "success",type = "redirect",location = "./pages/base/fixed_area.html")
    })
    public String associationCourier(){
        service.associateCourier(model,courierId,takeTimeId);
        return SUCCESS;
    }
}
